<template>
	<view class="common-bg">
		<view class="pad-20">
			<!-- #ifdef APP -->
			<uni-nav-bar :border="false" color="#222" backgroundColor="transparent" title="" />
			<!-- #endif -->
			<view class="flex flex-center flex-between">
				<view class="font-24 col-000-8 font-600">
					{{ $t('list.devices') }}
				</view>
				<view class="flex">
					<view class="msg-box" @click="doMsg">
						<uni-badge class=" uni-badge-left-margin" :text="msgNum" absolute="rightTop" :offset="[-3, -3]"
							size="small">
							<image class="msg-img" src="/static/svg/msg.svg" mode=""></image>
						</uni-badge>
					</view>
					<view class="add-box" @click="doAdd">
						<view class="add">
							<image class="img" src="/static/svg/add.svg" mode="widthFix"></image>
						</view>
					</view>
				</view>
			</view>
			<!-- 我的设备 -->
			<view class="devices-list">
				<view class="item" v-for="item in deviceList" :key="item.id" @click="doDetail(item)">
					<view class="device">
						<image v-if="item.device_status === 1" class="img" src="/static/svg/devices.svg" mode="widthFix"></image>
						<image v-else class="img" src="/static/svg/devices-000.svg" mode="widthFix"></image>
					</view>
					<view class="name font-500 font-16 col-000-8">
						{{item.device_name}}
					</view>
					<view class="status font-16 col-000-4">
						<span class="dot" :class="{'no': item.device_status == 0}"></span>
						{{item.device_status === 1 ? $t('list.online') : $t('list.offline') }}
					</view>
				</view>
			</view>
			<view class="empty-box" v-if="deviceList.length == 0">
				<view class="">
					<view class="empty-img">
						<image class="img-100" src="/static/svg/empty.svg" mode="widthFix"></image>
					</view>
					<view class="empty-text">
						{{ $t('list.noDevice') }}
					</view>
				</view>
			</view>
		</view>
	</view>
</template>
<script>
	import deviceApi from '@/api/device.js';
	import messageApi from '@/api/message.js';
	import deviceStatusMixin from '@/mixins/deviceStatusMixin.js';
	import myMqtt from '@/api/my-mqtt.js';

	import {store} from '@/uni_modules/uni-id-pages/common/store.js'
	
	export default {
		mixins: [deviceStatusMixin],

		data() {
			return {
				msgNum: 0,
				deviceList: []
			}
		},

		created() {
			// 只有在已登录状态下才调用需要权限的接口
			if (store.hasLogin) {
				this.getDeviceListApi();
				this.getMsgNum()
			} else {
				console.log('[DEVICE] 用户未登录,跳过设备列表和消息获取')
			}
			
			// 监听MQTT连接成功事件
			uni.$on('mqtt-connected', this.onMqttConnected)
		},
		
	onShow() {
		console.log('[DEVICE] 页面显示')
		// 只有在已登录状态下才调用需要权限的接口
		if (store.hasLogin) {
			this.getDeviceListApi();
			this.getMsgNum()
		}
		// 连接由 App.vue 的 onLaunch 和 onShow 统一管理
	},		onPullDownRefresh() {
			// 只有在已登录状态下才调用需要权限的接口
			if (store.hasLogin) {
				this.getDeviceListApi();
				this.getMsgNum()
			}
			setTimeout(function() {
				uni.stopPullDownRefresh();
			}, 1000);
		},
		onUnload() {
			// 页面卸载时停止设备监听
			if (this.deviceList.length > 0) {
				console.log('[DEVICE] 页面卸载，停止设备监听')
				myMqtt.stopDeviceMonitoring(this.deviceList)
			}
			
			// 移除MQTT连接事件监听
			uni.$off('mqtt-connected', this.onMqttConnected)
		},

		methods: {
			/**
			 * MQTT连接成功后的回调
			 */
			async onMqttConnected() {
				console.log('[DEVICE] 收到MQTT连接成功事件，启动设备监听')
				if (this.deviceList && this.deviceList.length > 0) {
					await myMqtt.startDeviceMonitoring(this.deviceList)
				} else {
					console.log('[DEVICE] 设备列表为空，跳过监听')
				}
			},
		/**
		 * 重写设备状态变化处理方法
		 * @param {string} deviceSn 设备序列号
		 * @param {Object} status 设备状态
		 */
		onDeviceStatusChange(deviceSn, status) {
			console.log('[DEVICE] 设备状态变化:', deviceSn, status)
			
			// 找到对应设备并更新状态（不区分大小写）
			const deviceSnLower = (deviceSn || '').toLowerCase()
			const deviceIndex = this.deviceList.findIndex(device => 
				(device.sn || '').toLowerCase() === deviceSnLower
			)

			if (deviceIndex !== -1) {
				const device = this.deviceList[deviceIndex]
				
				console.log(`[DEVICE] ✅ 找到设备 "${device.device_name}" (SN:${deviceSn})，当前状态:`, device.device_status)
				
				// 从 heartbeat 或 device 字段获取在线状态 (优先使用 heartbeat)
				let isOnline = false;
				
				// 1. 优先从 heartbeat 获取在线状态
				if (status.heartbeat && status.heartbeat.online !== undefined) {
					isOnline = status.heartbeat.online;
					console.log(`[DEVICE] "${device.device_name}" 从 heartbeat 获取在线状态:`, isOnline)
				}
				// 2. 从顶层 online 字段获取
				else if (status.online !== undefined) {
					isOnline = status.online;
					console.log(`[DEVICE] "${device.device_name}" 从 status.online 获取在线状态:`, isOnline)
				}
				// 3. 保持当前状态
				else {
					isOnline = device.device_status === 1;
					console.log(`[DEVICE] "${device.device_name}" 保持当前在线状态:`, isOnline)
				}
				
				const newStatus = isOnline ? 1 : 0;
				
				console.log(`[DEVICE] "${device.device_name}" 计算新状态: isOnline=${isOnline}, newStatus=${newStatus}, 当前=${device.device_status}`)

				// 更新设备在线状态 - 强制更新以确保UI刷新
				console.log(`[DEVICE] ✅ 更新设备 "${device.device_name}" 在线状态: ${device.device_status} -> ${newStatus}`)
				this.$set(this.deviceList[deviceIndex], 'device_status', newStatus)

				// 更新额外的设备信息
				if (status.heartbeat) {
					if (status.heartbeat.rssi !== undefined) {
						this.$set(this.deviceList[deviceIndex], 'signal_strength', status.heartbeat.rssi)
					}
					if (status.heartbeat.ts !== undefined) {
						this.$set(this.deviceList[deviceIndex], 'last_heartbeat', status.heartbeat.ts)
					}
				}
				
				if (status.device) {
					if (status.device.heap !== undefined) {
						this.$set(this.deviceList[deviceIndex], 'memory_usage', status.device.heap)
					}
					if (status.device.current_pattern) {
						this.$set(this.deviceList[deviceIndex], 'current_pattern', status.device.current_pattern)
					}
					if (status.device.wifi_rssi !== undefined) {
						this.$set(this.deviceList[deviceIndex], 'wifi_rssi', status.device.wifi_rssi)
					}
				}
			} else {
				console.warn(`[DEVICE] ❌ 未找到设备 SN=${deviceSn} 在设备列表中`)
				console.log('[DEVICE] 当前设备列表:', this.deviceList.map(d => `${d.device_name}(${d.sn})`))
			}
		},
		
		getMsgNum() {
			messageApi.getUnreadCount().then(res => {
				this.msgNum = res.unreadCount;
			})
		},

	async getDeviceListApi() {
		try {
			const res = await deviceApi.getDeviceList();
			if (res.errCode === 0) {
				console.log('[DEVICE] 获取设备列表成功:', res.data)
				
				// API不再返回device_status，所有状态都从MQTT缓存中获取
				// 这样确保状态始终是最新的，避免闪烁
				const processedDevices = res.data.map(device => {
					const cachedStatus = this.getDeviceCurrentStatus(device.sn)
					
					// 从缓存获取在线状态
					let deviceStatus = 0; // 默认离线
					
					if (cachedStatus) {
						// 优先从 heartbeat 获取在线状态
						if (cachedStatus.heartbeat && cachedStatus.heartbeat.online !== undefined) {
							deviceStatus = cachedStatus.heartbeat.online ? 1 : 0;
							console.log(`[DEVICE] 设备 ${device.sn} 从缓存heartbeat获取在线状态: ${deviceStatus}`)
						} else if (cachedStatus.device && cachedStatus.device.online !== undefined) {
							deviceStatus = cachedStatus.device.online ? 1 : 0;
							console.log(`[DEVICE] 设备 ${device.sn} 从缓存device获取在线状态: ${deviceStatus}`)
						} else {
							console.log(`[DEVICE] 设备 ${device.sn} 缓存中无在线状态，默认离线`)
						}
					} else {
						console.log(`[DEVICE] 设备 ${device.sn} 无缓存数据，默认离线`)
					}
					
					// 返回带有实时状态的设备对象
					return {
						...device,
						device_status: deviceStatus,
						signal_strength: cachedStatus?.heartbeat?.rssi || cachedStatus?.device?.wifi_rssi,
						memory_usage: cachedStatus?.device?.heap,
						current_pattern: cachedStatus?.device?.current_pattern,
						last_heartbeat: cachedStatus?.heartbeat?.ts
					}
				})
				
				// 一次性赋值，确保UI只渲染一次
				this.deviceList = processedDevices;
				
				// 启动设备监听（心跳+状态）
				if (myMqtt.isConnected() && this.deviceList.length > 0) {
					console.log('[DEVICE] MQTT已连接，立即启动设备监听，设备数量:', this.deviceList.length)
					await myMqtt.startDeviceMonitoring(this.deviceList)
				} else if (this.deviceList.length > 0) {
					console.log('[DEVICE] MQTT未连接，将在连接成功后启动监听')
				}
			} else {
				uni.showToast({
					title: res.errMsg || '获取设备列表失败',
					icon: 'none'
				});
			}
		} catch (error) {
			console.error('[DEVICE] 获取设备列表失败:', error)
			uni.showToast({
				title: '网络异常，请重试',
				icon: 'none'
			});
		}
	},			doAdd() {
				uni.navigateTo({
					url: '/pages/device/add-device'
				})
			},

			doMsg() {
				uni.navigateTo({
					url: '/pages/device/message-list'
				})
			},

			doDetail(device) {
				uni.navigateTo({
					url: '/pages/device/detail?sn=' + device.sn
				})
			}
		}
	}
</script>
<style lang="scss" scoped>
	.devices-list {
		width: 100%;
		margin: 80rpx auto 0;

		.item {
			width: 100%;
			background-color: #fff;
			box-shadow: 0px 0px 8rpx 0px rgba(0, 0, 0, 0.08);
			border-radius: 16rpx;
			padding: 48rpx 0;
			margin-bottom: 32rpx;
			transition: opacity 0.3s;

			.device {
				width: 80rpx;
				height: 60rpx;
				margin: 0rpx auto 0;

				.img {
					width: 100%;
					height: 100%;
				}
			}

			.name {
				margin: 16rpx auto 0;
				text-align: center;
			}

			.status {
				text-align: center;
				margin: 8rpx auto 0;

				.dot {
					width: 12rpx;
					height: 12rpx;
					border-radius: 100%;
					margin-right: 8rpx;
					display: inline-block;
					background-color: #22C55D;

					&.no {
						background-color: rgba(0, 0, 0, 0.4);
					}
				}
			}
		}
	}

	.msg-box,
	.test-box,
	.add-box {
		width: 68rpx;
		height: 68rpx;
		border-radius: 100%;
		background-color: #fff;
		display: flex;
		align-items: center;
		justify-content: center;
		margin-left: 16rpx;
	}

	.test-box {
		background-color: #10B981;

		.test-text {
			color: #fff;
			font-size: 24rpx;
			font-weight: 500;
		}
	}

	.msg-img {
		width: 36rpx;
		height: 44rpx;
	}

	.img {
		width: 40rpx;
		height: 40rpx;
	}

	.add-box {
		background-color: #3C82F6;
		margin-left: 16rpx;
		display: flex;
		align-items: center;
		justify-content: center;

		.add {
			width: 40rpx;
			height: 40rpx;

			.img {
				width: 100%;
				height: 100%;
			}
		}
	}
</style>